package com.wjc.service.user.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.wjc.hibernate.bean.ActiveStaus;
import com.wjc.hibernate.bean.User;
import com.wjc.hibernate.dao.UserDao;
import com.wjc.service.user.UserService;
import com.wjc.utils.mail.EmailUtil;
import com.wjc.utils.md5.MD5Util;

public class UserserviceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Override
	public String registryUser(User user) {
		// TODO Auto-generated method stub
		Map<String, Object> keyValues = new HashMap<>();
		keyValues.put("userName", user.getUserName());
		User userDB = userDao.find(keyValues);
		if (userDB != null) {
			return "exist";
		}
		user.setValidationCode(MD5Util.encode2hex(user.getEmail()));
		user.setRegistryTime(new Date());
		user.setActiveStatus(ActiveStaus.INACTIVE);
		userDao.persist(user);
		EmailUtil.sendEmail(user);
		return "needValidate";

	}

	@Override
	public String activate(User user, String activeCode) {
		Map<String, Object> keyValues = new HashMap<>();
		keyValues.put("email", user.getEmail());
		User userDb = userDao.find(keyValues);

		if (user != null) {

			if (userDb.getActiveStatus() == ActiveStaus.INACTIVE) {

				Date currentTime = new Date();

				currentTime.before(userDb.getRegistryTime());

				if (activeCode.equals(userDb.getValidationCode())) {

					userDb.setActiveStatus(ActiveStaus.ACTIVE);

					userDao.merge(userDb);
				}

			}
		}

		return null;
	}

	@Override
	public String loginUser(User user) {
		// TODO Auto-generated method stub
		List<User> users = userDao.findByExample(user);
		if (users.size() > 0) {
			return "success";
		} else {
			return "fail";
		}
	}
}
